package com.csylh.service.impl;

import com.google.common.collect.Lists;
import com.google.common.io.Files;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.Instant;
import java.util.List;

/**
 * Created by 留歌
 * Date: 2018/3/13 0:23
 * Description:
 */
@Service
public class FileService {

    @Value("${sunSpring.filepath}")
    private String filepath;

    public List<String> getImgPath(List<MultipartFile> fileList){
        List<String> pathList = Lists.newArrayList();
        fileList.forEach(file -> {
            File localFile = null;
            if(!file.isEmpty()){
                try{
                    localFile = saveToLocal(file);
                    String path = StringUtils.substringAfterLast(localFile.getAbsolutePath(),filepath);
                    pathList.add(path);
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        });

        return pathList;
    }

    private File saveToLocal(MultipartFile file) throws IOException{
        File newFile = new File(filepath+"/"+
                Instant.now().getEpochSecond()+"/"+file.getOriginalFilename());
        if(!newFile.exists()){
            newFile.getParentFile().mkdirs();
            newFile.createNewFile();
        }
        Files.write(file.getBytes(),newFile);
        return newFile;
    }

}
